package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.CustomerReservationMapper;
import com.zzyl.service.CustomerReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class CustomerReservationServiceImpl implements CustomerReservationService {
    @Autowired
    private CustomerReservationMapper crm;

    @Override
    public Integer getCancelledCount() {
        LocalDate today = LocalDate.now();
        Long userId = UserThreadLocal.getUserId();
        Integer count = crm.getCancelledCount(userId,today);
        return count;
    }

    @Override
    public List<ReservationVo> getCountByTime(LocalDateTime time) {
        LocalDate localDate = time.toLocalDate();
        List<ReservationVo> list = crm.getCountByTime(localDate);
        return list;
    }

    @Override
    public void addReservation(ReservationDto reservationDto) {
        Reservation reservation = BeanUtil.toBean(reservationDto, Reservation.class);
        Long userId = UserThreadLocal.getUserId();
        reservation.setStatus(0);
        reservation.setCreateBy(userId);

        try {
            crm.addReservation(reservation);
        } catch (Exception e) {
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }
    }

    @Override
    public PageResponse<ReservationVo> selectByPage(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        Long userId = UserThreadLocal.getUserId();
        Page page = (Page)crm.selectByPage(userId,status);
        PageResponse<ReservationVo> of = PageResponse.of(page, ReservationVo.class);
        return of;
    }

    @Override
    public void cancle(Long id) {
        crm.cancleReservation(id);
    }
}
